from datetime import datetime
from typing import Optional
from uuid import UUID, uuid4

from bisheng.database.base import session_getter
from bisheng.database.models.base import SQLModelSerializable
from sqlalchemy import Column, DateTime, String, Text, text, desc, func
from sqlmodel import Field, SQLModel


class UserChatBase(SQLModelSerializable):
    id: UUID = Field(nullable=False, primary_key=True, description='唯一ID')
    user_id: str = Field(sa_column=Column(String(length=255), default=""), description='用户id')
    chat_id: str = Field(sa_column=Column(String(length=255), default=''), description='会话id')
    chat_name: str = Field(sa_column=Column(String(length=255), default=''), description='会话名称')
    create_time: Optional[datetime] = Field(sa_column=Column(DateTime, nullable=False, server_default=text('CURRENT_TIMESTAMP')))
    update_time: Optional[datetime] = Field(sa_column=Column(DateTime,
                                                             nullable=False,
                                                             index=True,
                                                             server_default=text('CURRENT_TIMESTAMP'),
                                                             onupdate=text('CURRENT_TIMESTAMP')))


class UserChat(UserChatBase, table=True):
    id: UUID = Field(default_factory=uuid4, primary_key=True, unique=True)



class UserChatDao:
    @staticmethod
    def create_user_chat(user_chat: UserChat) -> UserChat:
        with session_getter() as session:
            # 确保 user_chat 有一个 UUID
            if not user_chat.id:
                user_chat.id = uuid4()

            session.add(user_chat)
            session.commit()
            session.refresh(user_chat)
            return user_chat

    @staticmethod
    def select_chat_by_user_id( user_id: str,page_size:int) -> list[UserChat]:
        with session_getter() as session:
            query = session.query(UserChat).filter(UserChat.user_id == user_id).order_by(desc(UserChat.create_time)).limit(page_size).all()
            return query

    @staticmethod
    def select_chat_by_chat_id_and_user_id(chat_id: str, user_id: str) -> Optional[UserChat]:
        with session_getter() as session:
            return session.query(UserChat).filter(UserChat.chat_id == chat_id,UserChat.user_id == user_id).first()

    @staticmethod
    def update_user_chat(user_chat: UserChat) -> UserChat:
        with session_getter() as session:
            user_chat = session.query(UserChat).filter(UserChat.chat_id == user_chat.chat_id, UserChat.user_id == user_chat.user_id).first()
            session.commit()
            session.refresh(user_chat)
            return user_chat
